from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Length, AnyOf, EqualTo, ValidationError
from flask_wtf.file import FileField, FileRequired, FileAllowed
from app.models.user import User
from flask_login import current_user
import re

# 设置API的表单不需要使用csrf
class BaseForm(FlaskForm):
    class Meta:
        csrf = False


# 获取用户token表单
class TokenForm(BaseForm):
    grant_type = StringField('授权类型', validators=[DataRequired('类型不能为空')])
    username = StringField('账号', validators=[DataRequired('账号不能为空'), Length(1, 255)])
    password = StringField('密码', validators=[DataRequired('密码不能为空'), Length(1, 255)])

    def validate_grant_type(self, field):
        if field.data.lower() != 'password':
            raise ValidationError('失败的token')


# 用户密码重置表单
class UserResetPassword(BaseForm):
    password = StringField('确认密码', validators=[DataRequired('密码不能为空'), Length(1, 255)])
    new_password = StringField('新密码', validators=[DataRequired('新密码不能为空'), Length(6, 255), EqualTo('new_password2', message="必须与确认密码一致")])
    new_password2 = StringField('新密码2', validators=[DataRequired('确认新密码不能为空'), Length(6, 255)])

    def validate_password(self, field):
        if not current_user.validate_password(field.data):
            raise ValidationError('密码不正确')

# 用户修改信息
class UserUpdateCompany(BaseForm):
    nickname = StringField('昵称', validators=[DataRequired('单位不能为空')])

# 图片上传
class FileUploadForm(BaseForm):
    upload = FileField('图片', validators=[FileRequired(), FileAllowed(['jpg', 'png', 'jpeg', 'gif'], '只允许上传图片')])
